<template>
	<view class="wrapper">
		<image :src="url" mode="widthFix" v-if="url"></image>
		<u-button type="primary" @click="upload" :customStyle="{
			width: '50%',
			marginTop: '20px'
		}">上传</u-button>
		<view class="options-wrapper">
			<view class="options">
				<!-- <view class="options-item">
					<view class="label">
						图片压缩质量
					</view>
					<u-slider v-model="value"></u-slider>
				</view> -->
			</view>
			<view class="btn-groups">
				<view class="btn" v-for="item in btnList" :key="item.id" @click="onBtnClick(item)">
					{{item.label}}
				</view>
			</view>
		</view>
		<u-loading-page :loading="isLoading" bg-color="rgba(0, 0, 0, .3)" loadingText="上传中"></u-loading-page>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				url: '',
				isLoading: false,
				btnList: [
					{
						id: 0,
						label: '图片黑白化',
						url: 'https://api.mg-tool.cn/v1/color-to-black/'
					},
					// {
					// 	id: 1,
					// 	label: '图片压缩',
					// 	url: 'https://api.mg-tool.cn/v1/ys/'
					// }
				]
			}
		},
		methods: {
			upload() {
				let that = this
				wx.chooseImage({
					success(res) {
						const tempFilePaths = res.tempFilePaths
						that.isLoading = true
						wx.uploadFile({
							url: 'https://picui.cn/api/v1/upload',
							filePath: tempFilePaths[0],
							name: 'file',
							header: {
								token: '480|uP9wwN17EGT01Ssagy4LKiMrjRLkuQ2GMnY2OGNR',
								Accept: 'application/json',
								'Content-Type': 'multipart/form-data'
							},
							formData: {
								file: tempFilePaths[0]
							},
							success(res) {
								that.url = JSON.parse(res.data).data.links.url
								that.isLoading = false
							},
							fail(err) {
								uni.showToast({
									title: err
								})
								that.isLoading = false
							}
						})
					}
				})
			},
			onBtnClick(item) {
				this.isLoading = true
				uni.request({
					url: item.url,
					method: 'get',
					data: {
						image: this.url
					},
					success: res => {
						this.isLoading = false
						console.log(res.data);
						this.url = res.data.file_path
					},
					fail: err => {
						this.isLoading = false
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.wrapper {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		/deep/ .u-button {
			width: 50%;
			margin: 20px 0;
		}

		image {
			width: 200px;
		}
		.btn-groups {
			display: flex;
			flex-wrap: wrap;
			margin: 20px auto;
			.btn {
				background: #3c9cff;
				padding: 4px 10px;
				border-radius: 4px;
				margin: 4px;
				color: #fff;
				font-size: 14px;
			}
		}
	}
</style>